// 导入axios

import axios from 'axios'

import {
  getToken
} from '@/utils/auth'
import {
  Toast
} from 'vant';
import router from '@/router'


axios.defaults.timeout = 3000
axios.defaults.baseURL = process.env.VUE_APP_URL

// 2.请求拦截器
axios.interceptors.request.use(config => {
  Toast.loading({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: '加载中',
  });
  let token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  // console.log(config)
  config.headers['content-type'] = 'application/json'
  return config
}, error => {
  Promise.reject(error)
})

// 3.响应拦截器
axios.interceptors.response.use(res => {
  // 调用失败
  if (res.code == 0) {
    Toast.clear()
  } else if ( res.code == 4800 ||res.code == 4500 ) {
    res.message && Toast(res.message)
  } else if (res.code == 4700) {
    // 未登录
    res.message && Toast(res.message)
    setTimeout(function () {
      router.push('/login')
      Toast.clear()
    }, 1000)
  } else{
    setTimeout(function () {
      Toast.clear()
    }, 1000)
  }

  return res

}, error => {
  if (error && error.response) {
    switch (error.response.status) {
      case 4700:

      case 400:
        error.message = '错误请求'
        break;
      case 401:
        error.message = '未授权，请重新登录'
        router.push('/login')
        break;
      case 403:
        error.message = '拒绝访问'
        break;
      case 404:
        error.message = '请求错误,未找到该资源'
        break;
      case 405:
        error.message = '请求方法未允许'
        break;
      case 408:
        error.message = '请求超时'
        break;
      case 500:
        error.message = '服务器端出错'
        break;
      case 501:
        error.message = '网络未实现'
        break;
      case 502:
        error.message = '网络错误'
        break;
      case 503:
        error.message = '服务不可用'
        break;
      case 504:
        error.message = '网络超时'
        break;
      case 505:
        error.message = 'http版本不支持该请求'
        break;
      default:
        error.message = `连接错误${error.response.status}`
    }
  } else {
    // 超时处理
    if (JSON.stringify(error).includes('timeout')) {
      Toast('服务器响应超时，请刷新当前页')
    }
    error.message('连接服务器失败')
  }
  // console.log(error, '错误信息')
  Toast(error.message)
  return Promise.resolve(error.response)
})

export function upload(url, params) {
  let resParams;
  resParams = {
    method: "post",
    url: url,
    data: params.data
  }
  return new Promise((resolve, reject) => {
    axios.post(url, resParams.data)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}
// 导入文件
export default axios
